package com.example.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author weiHuang.zhu
 * @Date 17/4/2023 下午9:35
 */
@Component
public class MyLB implements LoadBalance{

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public final int getAndIncrement() {
        int curent;
        int next;
        do {
            curent = this.atomicInteger.get();
            next = curent >= 2147483647 ? 0 :curent+1;

        }while (!this.atomicInteger.compareAndSet(curent, next));
        System.out.println("next:"+next);
        return next;
    }


    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        int index = getAndIncrement() % serviceInstances.size();

        return serviceInstances.get(index);
    }
}
